package cn.yunhe;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * Created by zs on 2017/11/30.
 * 测试Redis运算操作
 */
public class Demo4 {

    @Test
    public void test() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);

        //设置值
        redisTemplate.opsForValue().set("i", "9");
        printCurrValue(redisTemplate, "i");

        //原字段加1
        redisTemplate.opsForValue().increment("i", 1);
        printCurrValue(redisTemplate, "i");

        //原字段减1
        redisTemplate.getConnectionFactory().getConnection().decr(redisTemplate.getKeySerializer().serialize("i"));
        printCurrValue(redisTemplate, "i");

        //原字段减去指定数
        redisTemplate.getConnectionFactory().getConnection().decrBy(redisTemplate.getKeySerializer().serialize("i"), 6);
        printCurrValue(redisTemplate, "i");

        redisTemplate.opsForValue().increment("i", 2.3);
        printCurrValue(redisTemplate, "i");

    }


    /**
     * 打印当前key的值
     *
     * @param redisTemplate spring RedisTemplate
     * @param key
     */
    public static void printCurrValue(RedisTemplate redisTemplate, String key) {
        String i = (String) redisTemplate.opsForValue().get(key);
        System.err.println(i);
    }

}
